<?php

class access_rights {
 	
	private $ci;
	
 	public function __construct()
 	{
 		log_message('debug', 'Access rights library initialized.');
		
		$this->ci =& get_instance();
 	}
 	
	
	
	public function check_access($iUserId)
	{

		$sUri = $this->ci->uri->uri_string();
		$aUri = explode('/', $sUri);
		$iUri = count($aUri) - 1;

		/*********************************************************************************
		 * although the model should have already have been loaded, load it just in case *
		 ********************************************************************************/ 	
		$this->ci->load->model('db/views/user_admin_apps', 'vw_user_admin_apps');
		
			

		/***************************************************
		 * for each section of the url, working backwards, *
		 * determine if we have an app setup for it		   *
		 **************************************************/
		
		while ($iUri > 0)
		{
			$sUriPath = '';
			
			for ($i = $iUri; $i >= 1; $i--)
			{
				if ($aUri[$i] !== '')
				{
					if ($i === 2)
					{
						if (substr($aUri[$i], -5) === '_ajax') 
						{
							$aUri[$i] = substr($aUri[$i], 0, -5);		
						}
					}
					
					$sUriPath = '/'.$aUri[$i].$sUriPath;
				}
			}
			
			/*******************************************************************************************
			 * set the user id and app path based on the current URL that the user is trying to access *
			 ******************************************************************************************/
			$this->ci->vw_user_admin_apps->user_id = $iUserId;
			$this->ci->vw_user_admin_apps->app_path = $sUriPath;
			
			$qApps = $this->ci->vw_user_admin_apps->get(array(), 1);
			
			/**************************************************************************
			 * if  we've got a single row in the DB, then the user can access the app *
			 *************************************************************************/
			if ($qApps->num_rows() === 1)
			{
				return true;
			}
			
			$iUri--;
			
			
		}		
		 
		return false;
	}
	
	
	
	public function check_page_access($iUserId, $iGroupId, $iPageId, $sType = 'read')
	{
		return true;
	}
	
	
	public function check_media_folder_access($iUserId, $iGroupId, $iFolderId, $sType = 'read')
	{
		return true;	
	}
	
	
	
	public function get_security_group_apps($iGroupId)
	{
		$this->ci->db->select('sga.group_app_id, sga.group_id, aa.app_id, aa.app_ident, aa.app_pos, m.message_default AS app_text');
		$this->ci->db->from('admin_apps aa');
		$this->ci->db->join('messages m', 'aa.app_ident = m.message_ident');
		$this->ci->db->join('security_group_apps sga', 'sga.app_id = aa.app_id AND sga.group_id = '.$iGroupId, 'LEFT');
		$this->ci->db->order_by('aa.app_pos', 'ASC');
		
		$qSecGroupApps = $this->ci->db->get();
		
		return $qSecGroupApps;

	}
}